package grouplife::Controller::Users;
use Moose;
use namespace::autoclean;
use Catalyst::Request::Upload;
use Catalyst::Log;
use grouplife::Model::Users::UsersSearchModel;
use grouplife::Model::Users::UserRegisterModel;
use grouplife::Model::News::MyNewsModel;
use grouplife::Model::Comments::CommentsForUsersModel;
use grouplife::Model::UserUser::UserUserModel;
use grouplife::Model::UserStore::UserStoreModel;
use grouplife::Model::Tuan::TuansSearchModel;
use grouplife::Model::CommentedItem::CommentedItemModel;
use grouplife::Model::University::UniversityModel;
use grouplife::Model::TuanZhuanYi::TuanZhuanYiModel;
use Util::Email::SendEmail;
use Time::Piece;
use Digest::MD5;
use Encode;
use Email::Valid;
use Util::Token::Token;

BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Users - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

sub form_create :Chained('base') :PathPart('form_create') :Args(0) {
	my ($self, $c) = @_;
	my $universities = $c->model('University::UniversityModel')->get_all_univs;
	my $offices = $c->model('University::UniversityModel')->get_all_offices;
	my $houses = $c->model('University::UniversityModel')->get_all_houses;
	my $token = Util::Token::Token->new();
	$c->session->{token} = $token->generate_token();


	$c->stash(title => '用户注册');
	$c->stash(css => 'zhuce.css');
	$c->stash(universities => $universities);
	$c->stash(offices => $offices);
	$c->stash(token => $c->session->{token});
	$c->stash(houses => $houses);
	$c->stash(javascript => '/user/form_create.js');
	$c->stash(template => 'users/form_create.tt2');
}

sub user_total:Local {
        my ($self, $c) = @_;
        my $name = $c->request->params->{name} || '';
	my $count = $c->model('Users::UsersSearchModel')->user_search($name)->count;
	$c->res->output($count);
}

sub change_nick:Local {
        my ($self, $c) = @_;
        my $username = $c->request->params->{username} || '';
        my $university = $c->request->params->{university} || '';
        my $house = $c->request->params->{house} || '';
        my $office = $c->request->params->{office} || '';
	chomp $username;
	my $user = $c->session->{login_user};
	my $userobj = $c->model('Users::UsersSearchModel')->find($user->id);
	$userobj->update({username => $username, university_id=>$university, office_id=>$office, house_id=>$house});
	$c->session->{login_user} = $userobj;
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$user->id]));
}

sub change_photo:Local {
        my ($self, $c) = @_;
	my $image = $c->request->upload('image');
	my $user = $c->session->{login_user};
	my $userobj = $c->model('Users::UsersSearchModel')->find($user->id);
	my $user_new = $c->model('Users::UserRegisterModel')->change_photo($image, $c->config->{image_path}, $userobj);
	$c->session->{login_user} = $user_new;
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$user->id]));
}

sub change_passwd : Local {
	my ( $self, $c ) = @_;
	my $password= $c->request->params->{new_password} || '';
	my $user = $c->session->{login_user};
	my $userobj = $c->model('Users::UsersSearchModel')->find($user->id);
	$userobj->update({password => $password});
	$c->session->{login_user} = $userobj;
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$user->id]));
}
#################################################################################
#delete_buy_intention function
#################################################################################
sub delete_buy_intention:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
        my $store_id= $c->request->params->{store_id};
	my $user_store = $c->model('UserStore::UserStoreModel')->userstore_search($user_id, $store_id, 'T');
	unless($user_store->count == 0){
		$user_store->first->delete;
	}
	$c->res->output("success");
}

sub delete_renren_bind:Local {
        my ($self, $c) = @_;

	my $user = $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id);
	my @source_nick = $user->source_nick;
	foreach(@source_nick) {
		$_->delete() if($_->source_id eq '2');
	}
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$c->session->{login_user}->id]));
}
sub delete_taobao_bind:Local {
        my ($self, $c) = @_;

	my $user = $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id);
	my @source_nick = $user->source_nick;
	foreach(@source_nick) {
		$_->delete() if($_->source_id eq '1');
	}
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$c->session->{login_user}->id]));
}

#################################################################################
#Tuan function
#################################################################################
sub tuans_total:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
	$c->res->output($c->model('Tuan::TuansSearchModel')->find_tuans_for_user_count($user_id));
}

sub zhuanyis_total:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
	$c->res->output($c->model('TuanZhuanYi::TuanZhuanYiModel')->find_zhuanyis_for_user_count($user_id));
}

sub tuanzhang_total:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
	$c->res->output($c->model('TuanZhang::TuanZhangModel')->find_all_count());
}


sub zhuanyi_info :Local {
	my ($self, $c) = @_;
	
        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $user_id = $c->request->params->{user_id};
        my $page = int($start_index / 10);
        $page = $page + 1;
	my $user_role = 'X';
	if ($c->session->{login_user} and $user_id eq $c->session->{login_user}->id) {
		$user_role = 'S';
	}
	if ($user_role ne 'S') {
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(css   => 'zhuce.css');
                $c->stash(template => 'users/zhuanyi_info_failed.tt2');
	}
	my @requests = $c->model('TuanZhuanYi::TuanZhuanYiModel')->zhuanyi_request_search($user_id, $page); 
	$Template::Stash::PRIVATE = undef;
        $c->stash(
                login_user => $user_id,
                nowrapper => 1,
		user_role => $user_role,
		page => $page,
                template => 'users/zhuanyi_request_hist.tt2',
		zhuanyi_requests => \@requests 
        );
		
}

sub tuanzhang_info1 :Local {
	my ($self, $c) = @_;
	
        my $user_id = $c->request->params->{user_id};
	my $user_role = 'X';
	if (defined $c->session->{login_user} and $user_id eq $c->session->{login_user}->id) {
		$user_role = 'S';
	}
	if ($user_role ne 'S') {
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(css   => 'zhuce.css');
                $c->stash(template => 'users/zhuanyi_info_failed.tt2');
	}
	my @requestsR = $c->model('TuanZhang::TuanZhangModel')->find_by_status('R'); 
	my @requestsY = $c->model('TuanZhang::TuanZhangModel')->find_by_status('Y'); 
	my @requestsN = $c->model('TuanZhang::TuanZhangModel')->find_by_status('N'); 
	my @requestsC = $c->model('TuanZhang::TuanZhangModel')->find_by_status('C'); 
	$Template::Stash::PRIVATE = undef;
        $c->stash(
                login_user => $user_id,
                nowrapper => 1,
		user_role => $user_role,
                template => 'users/tuanzhang_request_hist.tt2',
		tuanzhang_requestsR => \@requestsR,
		tuanzhang_requestsY => \@requestsY, 
		tuanzhang_requestsN => \@requestsN, 
		tuanzhang_requestsC => \@requestsC 
        );
		
}

sub tuans_paging_list :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index} || '1';
        my $end_index = $c->request->params->{end_index} || '10';
        my $user_id = $c->request->params->{user_id};
	unless(defined($user_id)) {
		$user_id = $c->session->{login_user}->id; 
	}
	my $user = $c->model('Users::UsersSearchModel')->find($user_id);
	my $user_role = 'X';
	if ($user_id eq $c->session->{login_user}->id) {
		$user_role = 'S';
	}
	my $role = $c->model('UserTuan::UserTuanModel')->get_login_user_role_from_table($c->user, $c->session->{login_user});
	my $is_danwei_admin = $c->model('UserTuan::UserTuanModel')->is_danwei_admin($user_id,$c->session->{login_user}->id);

        my $page = int($start_index / 10);
        $page = $page + 1;
	my $current_time = localtime->strftime('%Y-%m-%dT%H:%M:%S');
	
	my @tuans = $c->model('Tuan::TuansSearchModel')->find_tuans_for_user($user_id, $page); 
	my $tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($user_id); 
	my $renzheng_status = 'U'; #'U'表示未提交申请
	if (defined $tuanzhang_info) {
		$renzheng_status = $tuanzhang_info->status;
	}
	my %arrayStatus;
	foreach my $tuan(@tuans) {
		my $Tstatus = $tuan->status;
		if($current_time lt $tuan->tihuo_time_from && $tuan->status eq 'Y') {
			$Tstatus = 'W';
		}
		if($current_time gt $tuan->tihuo_time_to && $tuan->status eq 'Y') {
			$Tstatus = 'J';
		}
		if($current_time ge $tuan->tihuo_time_from && $current_time le $tuan->tihuo_time_to && $tuan->status eq 'Y') {
			$Tstatus = 'P';
		}
		$arrayStatus{$tuan->id} = $Tstatus;
	}
	if(defined($user->university)) {
		$c->stash(univ_name => $user->university->name);
	} 
        $c->stash(
		title => '我的拼单',
                login_user => $user_id,
		user_role => $user_role,
		page => $page,
                template => 'users/tuangou_list.tt2',
		role => $role,
		is_danwei_admin => $is_danwei_admin,
		tuans => \@tuans,
		tuanstatus => \%arrayStatus,
		renzheng_status => $renzheng_status,
		tuanzhang_request => $tuanzhang_info,
		css=>'tuangou_list.css',
		current_time => $current_time 
        );
}

sub tuans_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index} || '1';
        my $end_index = $c->request->params->{end_index} || '10';
        my $user_id = $c->request->params->{user_id};
	my $user = $c->model('Users::UsersSearchModel')->find($user_id);
	my $user_role = 'X';
	if (defined $c->session->{login_user} and $user_id eq $c->session->{login_user}->id) {
		$user_role = 'S';
	}
	if (defined $c->session->{login_user}) {
		my $role = $c->model('UserTuan::UserTuanModel')->get_login_user_role_from_table($c->user, $c->session->{login_user});
		my $is_danwei_admin = $c->model('UserTuan::UserTuanModel')->is_danwei_admin($user_id,$c->session->{login_user}->id);
        	$c->stash(role => $role);
		$c->stash(is_danwei_admin => $is_danwei_admin);
	}

        my $page = int($start_index / 10);
        $page = $page + 1;
	my $current_time = localtime->strftime('%Y-%m-%dT%H:%M:%S');
	
	my @tuans = $c->model('Tuan::TuansSearchModel')->find_tuans_for_user($user_id, $page); 
	my $tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($user_id); 
	my $renzheng_status = 'U'; #'U'表示未提交申请
	if (defined $tuanzhang_info) {
		$renzheng_status = $tuanzhang_info->status;
	}
	my %arrayStatus;
	foreach my $tuan(@tuans) {
		my $Tstatus = $tuan->status;
		if($current_time lt $tuan->tihuo_time_from && $tuan->status eq 'Y') {
			$Tstatus = 'W';
		}
		if($current_time gt $tuan->tihuo_time_to && $tuan->status eq 'Y') {
			$Tstatus = 'J';
		}
		if($current_time ge $tuan->tihuo_time_from && $current_time le $tuan->tihuo_time_to && $tuan->status eq 'Y') {
			$Tstatus = 'P';
		}
		$arrayStatus{$tuan->id} = $Tstatus;
	}
	if(defined($user->university)) {
		$c->stash(univ_name => $user->university->name);
	}
        $c->stash(
                login_user => $user_id,
                nowrapper => 1,
		user_role => $user_role,
		page => $page,
                template => 'users/tuangou_hist.tt2',
		tuans => \@tuans,
		tuanstatus => \%arrayStatus,
		renzheng_status => $renzheng_status,
		tuanzhang_request => $tuanzhang_info,
		current_time => $current_time 
        );
}

#################################################################################
#News function
#################################################################################
sub news_total:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
	$c->res->output($c->model('News::MyNewsModel')->my_news($user_id)->count);
}

sub news_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $user_id = $c->request->params->{user_id};

        my $page = int($start_index / 20);
        $page = $page + 1;
        $c->stash(
                login_user => $user_id,
                nowrapper => 1,
                template => 'users/user_news.tt2',
		news_rs => $c->model('News::MyNewsModel')->my_news($user_id, $page)
        );
}

#################################################################################
#Comments function
#################################################################################
sub comments_total:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
	my $comments = $c->model('Comments::CommentsForUsersModel')->get_comments($user_id);
	$c->res->output(scalar(@$comments));
}

sub comments_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $user_id = $c->request->params->{user_id};

	my $user = $c->model('Users::UsersSearchModel')->find($user_id);
        my $page = int($start_index / 10);
        $page = $page + 1;
        $c->stash(
                login_user => $user_id,
                nowrapper => 1,
                template => 'users/user_comments.tt2',
		comments => $c->model('Comments::CommentsForUsersModel')->get_comments($user_id, $page)
        );
}

#################################################################################
#baobei function
#################################################################################
sub baobeis_total:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
	my $count = $c->model('Store::StoreSearchModel')->find_stores_by_owner_count($user_id);
	$c->res->output($count);
}

sub baobeis_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $user_id = $c->request->params->{user_id};
	my $user_role = 'X';
	if (defined $c->session->{login_user} and $user_id eq $c->session->{login_user}->id) {
		$user_role = 'S';
	}

        my $page = int($start_index / 10);
        $page = $page + 1;

	my $stores = $c->model('Store::StoreSearchModel')->find_stores_by_owner($user_id, $page);

        my %hash_zhuangtai;

        foreach my $store(@$stores) {
                my $store_id = $store->id;
                my $shenpi = $c->model('Store::StoreSearchModel')->get_shenpi_tuans($store_id);
                my $shenpi_count = scalar (@$shenpi);

                if($shenpi_count != 0) {
                        $hash_zhuangtai{$store_id} = 1;
                } else {
                        my $on_going = $c->model('Store::StoreSearchModel')->get_ongoing_tuans($store_id);
                        my $on_going_count= scalar (@$on_going);
                        $hash_zhuangtai{$store_id} = 1 if($on_going_count != 0);
                }
        }

        $c->stash(
                login_user => $user_id,
                nowrapper => 1,
		user_role => $user_role,
		page => $page,
		hash_zhuangtai => \%hash_zhuangtai,
                template => 'users/baobei_list.tt2',
		stores => $stores
        );
}

#################################################################################
#buyings function
#################################################################################
sub buys_total:Local {
        my ($self, $c) = @_;
        my $user_id = $c->request->params->{user_id};
	my $count = $c->model('Store::StoreSearchModel')->find_stores_buy_by_count($user_id);
	$c->res->output($count);
}

sub buys_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $user_id = $c->request->params->{user_id};
        my $login_user_role = 'X';
#already login
        if (defined $c->session->{login_user}) {
                $login_user_role = 'U';
        }
#self
	if(defined $c->session->{login_user} and $user_id eq $c->session->{login_user}->id) {
		$login_user_role = 'S';
	}

        my $page = int($start_index / 10);
        $page = $page + 1;
        $c->stash(
                login_user => $user_id,
                nowrapper => 1,
		login_user_role => $login_user_role,
		page => $page,
                template => 'users/buy_list.tt2',
		stores => $c->model('Store::StoreSearchModel')->find_stores_buy_by_status($user_id, $page)
        );
}

#################################################################################
#Autocomplete on user search page
#################################################################################
sub user_names:Local {
        my ($self, $c) = @_;
        my $p = $c->request->params->{q} || '';
        $c->res->output($c->model('Users::UsersSearchModel')->get_usernames_in_json($p));
}


sub user_paging:Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
        my $name = $c->request->params->{name} || '';

        my $page = int($start_index / 20);
        $page = $page + 1;

        $c->stash(
                login_user => $c->session->{login_user},
                nowrapper => 1,
                template => 'users/user_search.tt2',
		users => [$c->model('Users::UsersSearchModel')->user_search($name, $page)]
        );
}

sub user_search:Local {
        my ($self, $c) = @_;
        my $name = $c->request->params->{content} || '';
	my $members = $c->model('Users::UsersSearchModel')->user_search('', 1);
        $c->stash(
		login_user => $c->session->{login_user},
		javascript => '/user/user_search.js',
		content => $name,
		title => "搜索用户",
		good_members => $members,
		css => 'user_search.css',
		template => 'users/list.tt2'
        );
}

#################################################################################
#Friends functions
#################################################################################
sub join_friends : Local{
        my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $friend_id = $c->request->params->{"friend_id"}    || '';
	my $friend_name= $c->request->params->{"friend_name"}    || '';
        $c->stash(login_user => $c->session->{login_user});
        $c->stash(javascript => '/user/user_mainpage.js');
        $c->stash(nowrapper => 1);
        $c->stash(friend_id => $friend_id );
        $c->stash(friend_name => $friend_name );
        $c->stash(template => "users/join_friends.tt2");

}

sub accept_make_friends: Local{
        my ($self, $c) = @_;

	my $friend_id = $c->request->params->{"user_id"}    || '';
        my $friend_name = $c->model('Users::UsersSearchModel')->find($friend_id);
	my $me_id = $c->user->id;
	$c->model('UserUser::UserUserModel')->accept_friends($me_id, $friend_id);
	$c->user->add_to_my_news({user_id=>$c->user->id, photo=>$c->user->photo, event_type_id=>1, me_name=>$c->user->username, target_id=>$friend_id, target_name=>$friend_name->username});
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$me_id]));
}

sub refuse_make_friends: Local{
        my ($self, $c) = @_;

	my $friend_id = $c->request->params->{"user_id"}    || '';
	my $me_id = $c->user->id;
	$c->model('UserUser::UserUserModel')->refuse_friends($me_id, $friend_id);
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$me_id]));
}

sub join_friends_do : Local{
        my ($self, $c) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}
	my $friend_id = $c->request->params->{"friend_id"}    || '';
	my $me_id = $c->user->id;

	unless($c->model('UserUser::UserUserModel')->useruser_search($me_id, $friend_id)->count > 0) {
		$c->model('UserUser::UserUserModel')->add_to_users_users($me_id, $friend_id);
	}
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$friend_id]));
	
}

#################################################################################
#user information
#################################################################################
sub base :Chained('/') :PathPart('users') :CaptureArgs(0) {
        my ($self, $c) = @_;
}

sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
        my ($self, $c, $id) = @_;
        $c->stash(object => $c->model('Users::UsersSearchModel')->find($id));
        $c->stash(id => $id);
}

sub user_info :Chained('object') :PathPart('user_info') :Args(0) {
	my ($self, $c) = @_;

	my @my_tuans =  $c->model('Tuan::TuansSearchModel')->get_tuans_by_user($c->stash->{id}, 'S');

        my $login_user_role = 'X';
	if ($c->user_exists) {
		my $role = $c->model('UserTuan::UserTuanModel')->get_login_user_role_from_table($c->user, $c->session->{login_user});
		my $isAdmin = $c->model('UserTuan::UserTuanModel')->is_admin($c->user, $c->session->{login_user});
		my @arr_req;
	#already login
		if (defined $c->session->{login_user}) {
			$login_user_role = 'U';
		}
	#self
		if($c->user->id eq $c->stash->{id}) {
			$login_user_role = 'S';
		}
		if (defined $c->user) {
			@arr_req= $c->model('UserUser::UserUserModel')->useruser_search($c->user->id, $c->stash->{id});
		}
	#already send the invitation latter to make friends
		if (defined $arr_req[0]) {
			if($arr_req[0]->status eq 'R' or $arr_req[0]->status eq 'A') {
				$login_user_role = 'N';
			} elsif ($arr_req[0]->status eq 'Y') {
				$login_user_role = 'F';
			}
		}
		$c->stash(login_user => $c->session->{login_user}); 
		$c->stash(isAdmin => $isAdmin);
		$c->stash(role => $role);
	}

	my $renren_nick = '';
	my $taobao_nick = '';
	my @source_nick = $c->stash->{object}->source_nick;
	foreach(@source_nick) {
		if($_->source_id eq '2'){
			$renren_nick = $_->source_nick;
			$renren_nick = encode("gbk", decode_utf8($renren_nick));
			my @arr = split(/\|/, $renren_nick);
			$renren_nick = $arr[0];
		}
		if($_->source_id eq '1'){
			$taobao_nick = $_->source_nick;
		}
	}
	my $user_id = $c->stash->{object}->id;
	my $tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($user_id); 
	my $renzheng_status = 'U'; #'U'表示未提交申请
	if (defined $tuanzhang_info) {
		$renzheng_status = $tuanzhang_info->status;
		$c->stash(tuanzhang_info => $tuanzhang_info);
	}
	my $zhuanyi_count = 0;
	$zhuanyi_count = $c->model('TuanZhuanYi::TuanZhuanYiModel')->find_zhuanyis_for_user_count($user_id);

	my $universities = $c->model('University::UniversityModel')->get_all_univs;
	my $houses = $c->model('University::UniversityModel')->get_all_houses;
	my $offices = $c->model('University::UniversityModel')->get_all_offices;
	my $title = $c->stash->{object}->username . "的主页";
	$c->stash(user => $c->stash->{object},
		javascript => 'user/user_mainpage.js',
		css=>'user_mainpage.css',
		title=>$title,
		renren_nick=>$renren_nick,
		login_user_role=>$login_user_role,
		taobao_nick=>$taobao_nick,
		universities=>$universities,
		houses =>$houses,
		offices =>$offices,
		my_tuans => \@my_tuans,
        	renzheng_status => $renzheng_status,
		zhuanyi_count => $zhuanyi_count,
		show_news => 0,
		template => 'users/user_mainpage.tt2');
}

#################################################################################
#Check functions used at the registration page
#################################################################################
sub check_username : Local {
	my ( $self, $c ) = @_;
	my $username= $c->request->params->{username} || '';
	chomp $username;
	my $encoded = encode("utf8", $username); 
	unless($encoded =~ /^[A-Za-z0-9_\x80-\xff]+[^_]$/) {
                $c->res->output('false');
		return;	
	}
	if (defined($c->session->{login_user}) and $c->session->{login_user}->username eq $username ) {
                $c->res->output('true');
        } else {
		$c->res->output($c->model('Users::UsersSearchModel')->username_check($username));
	}
}
sub check_passwd : Local {
	my ( $self, $c ) = @_;
	my $password= $c->request->params->{old_password} || '';
	if ($c->authenticate({ email_address => $c->session->{login_user}->email_address, active => 'Y',password => $password  } )) {
		$c->res->output('true');
	} else {
		$c->res->output('false');
	}

}

sub check_email : Local {
	my ( $self, $c ) = @_;
	my $email= $c->request->params->{email} || '';
	$c->res->output($c->model('Users::UsersSearchModel')->email_check($email));
}

sub check_email_bind : Local {
	my ( $self, $c ) = @_;
	my $email= $c->request->params->{email} || '';
	$c->res->output($c->model('Users::UsersSearchModel')->email_check_2($email));
}

sub comment:Chained('base') :PathPart('comment') :Args(0){
    	my ( $self, $c ) = @_;

	if (!$c->user_exists) {
		$c->response->redirect($c->uri_for('/login'));
		$c->flash->{redirect_after_login} = '' . $c->req->uri;
		return 0;
	}

	my $comment = $c->request->params->{comment} || '';
	my $comm_id= $c->request->params->{comm_id} || '';
	my $user_id= $c->request->params->{user_id} || '';
	my $user= $c->model('Users::UsersSearchModel')->find($user_id);
	$c->model('CommentedItem::CommentedItemModel')->add_to_comments($comm_id, $c->user->get('id'), $comment);
        $c->user->add_to_my_news({user_id=>$c->user->getid, photo=>$c->user->photo, event_type_id=>7, me_name=>$c->user->username, target_id=>$user_id, target_name=>$user->username});

	$c->res->output('1');
}

#################################################################################
#Register
#################################################################################
sub register :Chained('base') :PathPart('register') :Args(0) {
	my ($self, $c) = @_;

	my $name = $c->request->params->{username} || '';
	my $password = $c->request->params->{create_password} || '';
	my $email= $c->request->params->{email} || '';
	my $fullname = $c->request->params->{fullname} || '';
	my $university = $c->request->params->{university} || '';
	my $source = $c->request->params->{source} || '';
	my $source_nick = $c->request->params->{source_nick} || '';
	my $office = $c->request->params->{office} || '';
	my $house = $c->request->params->{house} || '';
	my $get_token = $c->request->params->{token} || '';

        my $session_token = $c->session->{token};
        my $token = Util::Token::Token->new();
        $c->session->{token} = $token->generate_token();
        if($get_token eq $session_token) {
		my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('1');

		my $image = $c->request->upload('image');
		$email =~ s/^\s+//;
		$email =~ s/\s+$//;
		$name =~ s/^\s+//;
		$name =~ s/\s+$//;

		my $error_msg = "0";
		unless(Email::Valid->address("$email")){
			$error_msg = "邮箱无效";
		} else {
			my @exist_users = $c->model('Users::UsersSearchModel')->get_user_by_email($email);
			if(scalar(@exist_users) > 0) {
				$error_msg = "该邮箱已被注册";
			}
		}
		
		my $encoded = encode("utf8", $name); 
		unless($name =~ /^[A-Za-z0-9_\x80-\xff]+[^_]$/) {
			$error_msg = "昵称无效";
		} else {
			if(length($name) > 12) {
					$error_msg = "该昵称过长";
			} else {
				my @exist_users = $c->model('Users::UsersSearchModel')->get_user_by_username($name);
				if(scalar(@exist_users) > 0) {
					$error_msg = "该昵称已被注册";
				}
			}
		}
		
		if($error_msg ne "0"){
			my $universities = $c->model('University::UniversityModel')->get_all;
			$c->stash(title => '用户注册');
			$c->stash(css => 'zhuce.css'),
			$c->stash(error_msg => $error_msg),
			$c->stash(universities => $universities),
			$c->stash(javascript => '/user/form_create.js');
			$c->stash(template => 'users/form_create.tt2');
			return;	
		}

		my $user = $c->model('Users::UserRegisterModel')->register($image, $name, $password, $fullname, $commented_item->id, $email, $c->config->{image_path}, $source, $source_nick, $university, $office, $house);
		if($source eq '2'){
			$c->session->{login_user} = $user;
			$c->stash(login_user => $c->session->{login_user}),
			$c->stash(username => $name),
			$c->stash(source => $source),
			$c->stash(source_nick => $source_nick),
			$c->stash(css =>'zhuce.css'),
			$c->stash(css => 'main_page.css');
			$c->stash(javascript => '/mainpage/main_page.js');
			$c->stash(title => '拼单族 - 爱拼才汇营！');
			$c->stash(template => 'index.tt2');

		}else{

			my $md5 = Digest::MD5->new;
			$md5->add($email);
			my $conf_url = $c->config->{verification_url} . "?uid=" . $user->id . "&code=" . $md5->hexdigest;
			my (%params, %options);
			$options{INCLUDE_PATH} = $c->config->{email_template_path};
			$params{username} = $name;
			$params{email}  = $email;
			$params{conf_url} = $conf_url;
			$params{create_time} = $user->created;

			my $title = "欢迎加入拼单族";
			my $sender = Util::Email::SendEmail->new();
			my $template = "email/register.html.tt";
			$sender->send($email, $title, $template, \%params, \%options);
			$c->stash(username  => $name);
			$c->stash(email => $email);
			$c->stash(css 	=> 'zhuce.css');
			$c->stash(template => 'users/register_success.tt2');
		}
	} else {
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'resubmit/resubmit.tt2');
	}

}

sub renrenlogin :Chained('base') :PathPart('renrenlogin') :Args(0) {
        my ($self, $c) = @_;

        my $name = $c->request->params->{username} || '';
        my $password = $c->request->params->{create_password} || '';
        my $email= $c->request->params->{email} || '';
        my $fullname = $c->request->params->{fullname} || '';
        my $source = $c->request->params->{source} || '';
        my $source_nick = $c->request->params->{source_nick} || '';

        my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('1');
        my $image = $c->request->upload('image');

        my $user = $c->model('Users::UserRegisterModel')->register($image, $name, $password, $fullname, $commented_item->id, $email, $c->config->{image_path}, $source, $source_nick);
	$user->update({active => 'Y'});
        $c->authenticate({ email_address => $user->email_address, active => 'Y', password => $password  } );
	$c->session->{login_user} = $user;
	$c->response->redirect($c->uri_for($c->controller('Users')->action_for('user_info'), [$user->id]));
}


sub taobao_bind  :Chained('base') :PathPart('taobao_bind') :Args(0) {
	my ($self, $c) = @_;

	my $source = $c->request->params->{source} || '';
	my $source_nick = $c->request->params->{source_nick} || '';
	my $nick = $c->request->params->{nick} || '';
	my $title = '';
	if($source eq '1') {
		$title = "淘宝账户绑定";
		$c->stash(source_nick => $nick);
	} elsif($source eq '2') {
		$title = "人人账户绑定";
		$c->stash(source_nick => $source_nick);
	} elsif($source eq '3') {
		$title = "QQ账户绑定";
		$c->stash(source_nick => $source_nick);
	}
	
	$c->stash(source => $source);
	$c->stash(title  => $title);
	$c->stash(nick => $nick);
	$c->stash(css 	=> 'zhuce.css');
	$c->stash(javascript => '/taobao/taobao_bind.js');
        $c->stash(template => 'taobao/taobao_bind.tt2');
}

sub taobao_bind_do  :Chained('base') :PathPart('taobao_bind_do') :Args(0) {
	my ($self, $c) = @_;

	my $source = $c->request->params->{source} || '';
	my $source_nick = $c->request->params->{source_nick} || '';
	my $nick = $c->request->params->{nick} || '';
	my $email = $c->request->params->{email} || '';
	
	my @users = $c->model('Users::UsersSearchModel')->get_user_by_email($email);
	my $user = $users[0];
	my (%params, %options);
	$options{INCLUDE_PATH} = $c->config->{email_template_path};
        $params{username} = $user->username;
        $params{source_nick} = $source_nick;
        $params{nick} = $nick;
        $params{source} = $source;
        $params{email}  = $user->email_address;

	my $md5 = Digest::MD5->new;
	$md5->add($user->email_address);
	$md5->add($source_nick);

	my $bind_url = $c->config->{taobao_bind_url} . "?source=" . $source . "&source_nick=" . $source_nick. "&email=" . $user->email_address . "&code=" . $md5->hexdigest;
        $params{request_url}  = $bind_url;

	my $title = '';
	if($source eq '1') {
		$title = "淘宝账户绑定请求";
	} elsif($source eq '2') {
		$title = "人人账户绑定请求";
	} elsif($source eq '3') {
		$title = "QQ账户绑定请求";
	}
	my $sender = Util::Email::SendEmail->new();
	my $template = "email/taobao_bind_request.html.tt";
	$sender->send($user->email_address, $title, $template, \%params, \%options);

	$c->stash(email => $user->email_address,
			username => $user->username,
			css => 'denglu.css',
			template => "users/taobao_bind_success.tt2");
}

=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
